package club.zbiao.modules.system.service.spec;

import club.zbiao.modules.system.domain.Dept;
import club.zbiao.modules.system.service.dto.DeptDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by zhb on 2019/5/23.
 */
@Component
public class DeptSpec implements BaseSpec<DeptDTO,Dept> {

    private DeptDTO dept;

    private Set<Long> deptIds;


    public void init(DeptDTO dept){
        this.dept = dept;
        this.deptIds = dept.getDeptIds();
    }

    @Override
    public Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

        List<Predicate> list = new ArrayList<Predicate>();

        if(!ObjectUtils.isEmpty(dept.getName())){
            /**
             * 模糊
             */
            list.add(cb.like(root.get("name").as(String.class),"%"+dept.getName()+"%"));
        }

        if(!ObjectUtils.isEmpty(dept.getEnabled())){
            /**
             * 相等
             */
            list.add(cb.equal(root.get("enabled").as(Boolean.class),dept.getEnabled()));
        }

        if(!ObjectUtils.isEmpty(dept.getPid())){
            /**
             * 相等
             */
            list.add(cb.equal(root.get("pid").as(Boolean.class),dept.getPid()));
        }

        if (!CollectionUtils.isEmpty(deptIds)) {
            list.add(root.get("id").in(deptIds));
        }

        Predicate[] p = new Predicate[list.size()];
        return cb.and(list.toArray(p));
    }
}
